var express = require('express')
var router = express.Router()
var mssqldb = require('../../Sql/Sql')
var jwt = require('jsonwebtoken')
var m5 = require("md5");

// 登录
router.post('/api/login', function (req, res) {
  mssqldb.sql(`select top 1 * from Users where telephone = ${req.body.telephone}`, function (err, result) {
    if (err) {
      console.log(err)
      return
    }
    // 登录失败，帐号密码错误
    if (result.rowsAffected[0] === 0 || (result.rowsAffected[0] === 1 && m5(m5(req.body.password)) !== result.recordset[0].password)) {
      console.log(result.recordset[0].password)
      let response = {
        errorCode: 1, // 帐号或密码错误
      }
      res.send(response)
      return
    }
    // 登录成功
    //jwt生成加密token，telephone是公文，密钥是“secret”，1小时后过期
    token = jwt.sign({
      telephone: result.recordset.telephone
    }, "secret", {
      expiresIn: 60 * 60
    });
    let response = {
      errorCode: 0, // 登录成功
      data: {
        username: result.recordset[0].username,
        telephone: result.recordset[0].telephone,
        email: result.recordset[0].email,
        gender: result.recordset[0].gender,
        token: token
      }
    }
    res.send(response)
  })
})

// 注册用户
router.post('/api/register', function (req, res) {
  // 先检查是否存在手机号，若存在不允许注册
  mssqldb.sql(`select top 1 * from Users where telephone = ${req.body.telephone}`, function (err, result) {
    if (err) {
      console.log(err)
      return
    }
    // 注册失败，手机号已存在
    if (result.rowsAffected[0] !== 0) {
      let response = {
        errorCode: 1, // 手机号已经存在
      }
      res.json(response)
      return
    }
    var pwd = m5(m5(req.body.password));
    // 当不存在帐号时注册
    mssqldb.sql(`insert into Users values('${req.body.username}','${req.body.telephone}','${pwd}','${req.body.email}','${req.body.gender}')`, function (err, result) {
      if (err) {
        console.log(err)
        return
      }
      // 注册的同时就要先建立一个 ‘我的钱包’ 账户，该账户不可删除
      mssqldb.sql(`insert into Accounts values('${req.body.telephone}','我的钱包',0,'',1)`, function (err, result) {
        if (err) {
          console.log(err)
          return
        }
      })
      // 注册成功
      let response = {
        message: '成功',
        data: {
          status: 200,
          errorCode: 0, // 注册成功
        }
      }
      res.json(response)
    })
  })

})

// 更新基本信息
router.put('/api/update', function (req, res) {
  mssqldb.sql(`update Users set username='${req.body.username}',email='${req.body.email}',gender='${req.body.gender}' where telephone='${req.body.telephone}'`, function (err, result) {
    if (err) {
      console.log(err)
      return
    }
    mssqldb.sql(`select top 1 * from Users where telephone = ${req.body.telephone}`, function (err, _result) {
      if (err) {
        console.log(err)
        return
      }
      let response = {
        errorCode: 0, // 更新成功
        data: {
          username: _result.recordset[0].username,
          telephone: _result.recordset[0].telephone,
          email: _result.recordset[0].email,
          gender: _result.recordset[0].gender
        }
      }
      res.json(response)
    })
  })
})

// 修改密码
router.put('/api/password', function (req, res) {
  mssqldb.sql(`select top 1 * from Users where telephone = ${req.body.telephone}`, function (err, result) {
    if (err) {
      console.log(err)
      return
    }
    // 登录失败，帐号密码错误
    if (result.rowsAffected[0] === 0 || (result.rowsAffected[0] === 1 && req.body.oldPassword !== result.recordset[0].password)) {
      let response = {
        errorCode: 1, // 原密码错误
      }
      res.json(response)
    }
    // 原密码正确
    mssqldb.sql(`update Users set password='${req.body.newPassword}' where telephone='${req.body.telephone}'`, function (err, result) {
      if (err) {
        console.log(err)
        return
      }
      mssqldb.sql(`select top 1 * from Users where telephone = ${req.body.telephone}`, function (err, _result) {
        if (err) {
          console.log(err)
          return
        }
        let response = {
          errorCode: 0 // 修改密码成功
        }
        res.json(response)
      })
    })
  })
})


router.delete('/api/deleteAll/:telephone', function (req, res) {
  mssqldb.sql(`delete from Accounts where telephone = ${req.params.telephone}`, function (err, result) {
    if (err) {
      console.log(err)
      let response = {
        errorCode: 1 // 错误
      }
      res.send(response)
      return
    }
    // 删除的同时就要先建立一个 ‘我的钱包’ 账户
    mssqldb.sql(`insert into Accounts values('13822223333','我的钱包',0,'',1)`, function (err, result) {
      if (err) {
        console.log(err)
        return
      }
    })
  })
  mssqldb.sql(`delete from Tallys where telephone = ${req.params.telephone}`, function (err, result) {
    if (err) {
      console.log(err)
      let response = {
        errorCode: 1 // 错误
      }
      res.send(response)
      return
    }
  })

  let response = {
    errorCode: 0, // 成功
  }
  res.json(response)
})


module.exports = router